<?php
namespace system;

/**
 * Dispatcher class - responsible for determining what controller/action to be take per request
 * 
 * @author milena
 *        
 */
class Dispatcher
{

    private $request;

    public function __construct($request)
    
    {
        $this->request = $request;
    }

    public function dispatch()
    {
        $response = null;
        $command = $this->request->getCommandName();
        $controllerName = "\controller\\" . ucfirst(strtolower($command)) . "Controller";
        $controller = new $controllerName();
        
        if (class_exists($controllerName)) {
            $params = $this->request->getParameters();
            $id = isset($params[0]) && $params[0] == 'id' ? $params[1] : null; // this is a pseudo ID, since we have no real database
            switch ($this->request->getMethod()) {
                case "GET":
                    $response = $controller->executeGet($id);
                    break;
                case "POST":
                    $post_vars = $_POST;
                    $response = $controller->executeCreate($post_vars);
                    break;
                case "PUT":
                    parse_str(file_get_contents("php://input"), $post_vars);
                    $response = $controller->executeUpdate($id, $post_vars);
                    break;
                case "DELETE":
                    $response = $controller->executeDelete($id);
                    break;
            }
        } else {
            $response = $controller->execute404();
        }
        return $response;
    }
}